package com.example.springboottest.example.kafka.simple;

import com.example.springboottest.example.kafka.simple.topiccommand.KafkaListener;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;

import java.time.Duration;

import java.util.Collections;
import java.util.Properties;

/**
 * 当消费者属于同一个组的时候，只会接收到一次消息，反之，会各个收到
 * 当消息发布到主题后，只会被投递给订阅它的每个消费组中的一个消费者
 */
public class ConsumerFastStart {
    public static final String brokerList = "localhost:9092";
    public static final String topic = "topic-demo3";
    public static final String groupId = "group.demo";

    public static void main(String[] args) {
        System.out.println(Duration.ofMillis(1000).toMillis());
        Properties properties = new Properties();
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put("bootstrap.servers", brokerList);

        //设置消费组的名称
        properties.put("group.id", groupId);

        // 创建一个消费者客户端实例
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);

        //订阅主题
//        consumer.subscribe(Collections.singletonList(topic));
        consumer.subscribe(Collections.singletonList(topic), new KafkaListener());

        //循环消费消息
        while (true) {
            System.out.println("while (true)");
            System.out.println(Duration.ofMillis(1000));
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(5000));
            for (ConsumerRecord<String, String> record : records) {
                System.out.println(record.value());
            }
        }
    }
}